// src/views/excel/Import.jsx
import React, { useState, useRef } from 'react'
import { Space, Button, Table, Input} from 'antd'
// 1.引入模块
import * as XLSX from 'xlsx'
function Com() {
  const [proList, setProList] = useState([])
  const columns = [
    {
      title: '序号',
      render: (text, record, index) => <span>{ index + 1 }</span>
    },
    {
      title: '产品名称',
      dataIndex: 'proname'
    },
    {
      title: '图片',
      dataIndex: 'img1',
      render: (text, record, index) => <img src={text} alt='123' />
    }
  ]
  const fileRef = useRef()
  const selectFile = () => {
    fileRef.current.input.click()
  }

  const selectFileInfo = () => {
    // 2.读取excel文件信息
    const file = fileRef.current.input.files[0]
    const reader = new FileReader()
    reader.readAsBinaryString(file) // 读取文件二进制
    reader.onload = function () {
      // 3，转换数据
      const workbook = XLSX.read(this.result, { type: 'binary' });
      const t = workbook.Sheets['工作表1']
      const r = XLSX.utils.sheet_to_json(t)
      // 上传 r 数据到数据库，一旦数据库保存完毕执行以下代码
      setProList(r)
    }
  }
  return (
    <div>
      <h1>导入</h1>
      <Space direction="vertical" style={{ width: '100%'}}>
        <Button onClick = { selectFile }>上传文件</Button>
        <Input ref={fileRef} hidden type="file" onChange = { selectFileInfo }></Input>
        <Table rowKey="proid" dataSource={proList} columns = { columns }></Table>
      </Space>
    </div>
  )
}

export default Com